﻿(function ($) {

    $(function () {
        var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
        $.getScript(scriptbase + "SP.js", function () {
            $.getScript(scriptbase + "SP.Taxonomy.js", getcalendaritem('yourCalendarcontent'));
        });
    });

    /*javascript for Mark Your Calendar*/
    this.getcalendaritem = function (idcontent) {
        $('#markYourCalendarloading').show();
        var currentId = 'markYourCalendar';
        var itemrowlimit = getRowLimitFromContentEditorWP(currentId);
        var siteUrl = '/teams/OurVoiceHN/UpcomingEvents/';
        var clientContext = new SP.ClientContext(siteUrl);
        var oList = clientContext.get_web().get_lists().getByTitle('Posts');
        var camlQuery = new SP.CamlQuery();

        camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Is_x0020_Active\' /><Value Type=\'Boolean\'>1</Value></Eq><Geq><FieldRef Name=\'PublishedDate\' /><Value Type=\'DateTime\'><Today /></Value></Geq></And></Where><OrderBy><FieldRef Name=\'PublishedDate\' Ascending=\'FALSE\' /></OrderBy></Query><RowLimit>' + itemrowlimit + '</RowLimit></View>');
        var items = oList.getItems(camlQuery);
        clientContext.load(items, "Include(ID,Title,Location,Summary,PublishedDate,Author,AuthorName,PublishingPageIcon)");
        clientContext.executeQueryAsync(
            function () {
                var listEnumerator = items.getEnumerator();
                $('#' + idcontent).html('');
                $('#markYourCalendarloading').hide();
                var count = 0;

                while (listEnumerator.moveNext()) {
                    count++;
                    var calendarId = 'msCalendar_' + count;
                    var addToCalendarId = 'addToCalendar_' + count;

                    var item = listEnumerator.get_current();
                    var url = siteUrl + 'Lists/Posts/Post.aspx?ID=' + item.get_item('ID');

                    //get values
                    var titleValue = item.get_item('Title');
                    var locationValue = item.get_item('Location');
                    if (locationValue == null) locationValue = '';

                    var startDate = item.get_item('PublishedDate');
                    var endDate = item.get_item('PublishedDate');
                    var description = item.get_item('Summary');

                    var calendar = buildcalendaritem(new Date(startDate), item.get_item('Title'), item.get_item('PublishingPageIcon'), description, url, calendarId, addToCalendarId);
                    $('#' + idcontent).append(calendar);

                    //----Add to my calendar
                    AddToOutlook(titleValue, startDate, endDate, locationValue, description, calendarId, addToCalendarId);
                }
                if ($('#' + idcontent).html() == '') {
                    $('#' + idcontent).html('There are no posts in this category.');
                }

            }, function (sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );

    };

    this.buildcalendaritem = function (dateCalendar, author, pathurl, content, urlitem, calendarId, addToCalendarId) {
        if (content == null) {
            content = "";
        }

        if (content.length > 130) {
            content = content.substring(0, 130);
        }

        var imgurl = "";
        if (pathurl != null && $(pathurl).attr('src') != "") {
            imgurl = $(pathurl).attr('src') + '?RenditionID=7';
        }
        else {
            imgurl = '/teams/OurVoiceHN/Style Library/Images/default_image.gif?RenditionID=7';
        }
        if (author == null)
            author = "";
        var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat'];
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

        var result = '<div class="calendaritem col-sm-4 col-md-4 col-lg-4">';
        result += '<div class="row">';
        result += '<div class="titleCalendar col-sm-12 col-md-12 col-lg-12">';

        result += '<div class="dateSection">';
        result += '<h5 class="dayCalendar">' + days[dateCalendar.getDay()] + '</h5>';
        result += '<h3 class="dateCalendar">' + dateCalendar.getDate() + '</h3>';
        result += '<h5 class="monthCalendar">' + months[dateCalendar.getMonth()] + '</h5>';
        result += '</div>';

        result += '<div class="author">' + author + '</div>';
        result += '</div>';

        result += '<div class="col-sm-12 col-md-12 col-lg-12"><a href="' + urlitem + '"><img class="img-responsive" src="' + imgurl + '" /></a></div>';

        result += '<div class="caption col-sm-12 col-md-12 col-lg-12">';
        result += '<h5 class="time">' + formatAMPM(dateCalendar) + '</h5>';
        result += '<p class="content">' + content + '</p>';
        result += '<a class="moreInfor" href="' + urlitem + '">More »</a>';
        result += '</div>';

        result += '<div id=\"' + addToCalendarId + '" class="addToCalendar col-sm-12 col-md-12 col-lg-12"></div>';
        result += '<div id=\"' + calendarId + '\"></div>';

        result += '</div>';
        result += '</div>';
        return result;
    };

    this.formatAMPM = function (date) {
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var ampm = hours >= 12 ? 'PM' : 'AM';
        hours = hours % 12;
        hours = hours ? hours : 12; // the hour '0' should be '12'
        minutes = minutes < 10 ? '0' + minutes : minutes;
        var strTime = hours + ':' + minutes + ' ' + ampm;
        return strTime;
    };

    this.AddToOutlook = function (title, eventDate, endDate, location, description, calendarId, addToCalendarId) {
        //------Add to my calendar
        var myCalendar = createCalendar({
            options: {
                id: calendarId                               // You need to pass an ID. If you don't, one will be generated for you.
            },
            data: {
                title: title.toString(),     // Event title
                start: new Date(eventDate),   // Event start date
                duration: 120,                            // Event duration (IN MINUTES)
                end: new Date(endDate),     // You can also choose to set an end time.
                // If an end time is set, this will take precedence over duration
                address: location.toString(),
                description: description.toString().replace(/(\r\n|\n\r|\r|\n)/g, " ")
            }
        });

        document.querySelector('#' + calendarId).appendChild(myCalendar);

        //remove redundant icons
        var iconoutlookClass = $('#' + calendarId).find('a.icon-outlook');
        if (iconoutlookClass !== null && iconoutlookClass.length > 0) {
            iconoutlookClass.text('Add to outlook');
            $('#' + addToCalendarId).html(iconoutlookClass);

            if ($('#' + calendarId).length > 0) $('#' + calendarId).remove();
        }

        if (navigator.userAgent.search("MSIE") >= 0) {
            $(".addToCalendar").addClass("hide");
        }
    };

    /*end javascript for Mark Your Calendar*/
    /*=======================================*/
}).call(this, jQuery);